package com.zy.search.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zy.common.util.ExceptionUtil;
import com.zy.common.util.TaotaoResult;
import com.zy.search.pojo.Item;
import com.zy.search.pojo.SearchResult;
import com.zy.search.service.SearchService;

//商品查询
@Controller
public class SearchController {

	@Autowired
	private SearchService searchService;

	@RequestMapping(value = "/query", method = RequestMethod.GET)
	@ResponseBody
	public TaotaoResult search(@RequestParam("q") String queryString, @RequestParam(defaultValue = "1") Integer page,
			@RequestParam(defaultValue = "60") Integer rows) {
		// 查询条件不能为空
		if (StringUtils.isBlank(queryString)) {
			return TaotaoResult.build(400, "查询条件不能为空");
		}
		SearchResult searchResult = null;
		try {
			// get方法传递参数 q 的时候会乱码
			queryString = new String(queryString.getBytes("iso-8859-1"), "utf-8");
			searchResult = searchService.search(queryString, page, rows);
		} catch (Exception e) {
			e.printStackTrace();
			return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
		}
		return TaotaoResult.ok(searchResult);
	}
	
	@RequestMapping(value = "/queryById")
	@ResponseBody
	public TaotaoResult queryItemById(@RequestParam("q")String id) throws Exception {
		Item queryItemById = searchService.queryItemById(id);
		return TaotaoResult.ok(queryItemById);
	}

}
